import React, { useState, useEffect,useRef  } from 'react';
import { Table, Button, Form,message, Space,Tag,Tooltip} from 'antd';
import { EditOutlined, DeleteOutlined} from '@ant-design/icons';
import { getUsers, addUser, updateUser, deleteUser,getExportUsers} from 'services/user';
import { getRoles } from 'services/role';
// import './index.css';
import { ROLE_NAMES,ROLE_COLORS  } from 'constants/roles';
import UserModal from './UserModal';
import SearchForm from 'components/SearchForm';

const Users = () => {
  const [users, setUsers] = useState([]);
  const [roles, setRoles] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [queryForm] = Form.useForm();
  const [editingUser, setEditingUser] = useState(null);
  const [total, setTotal] = useState(0);  // 数据总数
  const [page, setPage] = useState(1);    // 当前页
  const [pageSize, setPageSize] = useState(10);  // 每页数据条数
  const [isSuperAdmin, setIsSuperAdmin] = useState(false);
  const [tableHeight, setTableHeight] = useState(400); // 初始表格高度为 400
  const containerRef = useRef(null); // 定义 ref
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 选中的行
  const [exportLoading, setExportLoading] = useState(false);
  const [messageApi, contextHolder] = message.useMessage(); // 使用 message hook
 

  useEffect(() => {
    updateTableHeight();
    window.addEventListener("resize", updateTableHeight); // 监听窗口大小变化
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    setIsSuperAdmin(userInfo.role === 'super_admin');
    form.resetFields();
    fetchUsers({page,pageSize});
    fetchRoles();
    return () => {
      window.removeEventListener("resize", updateTableHeight); // 清理事件监听器
    };
  }, []);
  // 计算表格的高度
  const updateTableHeight = () => {
    if (containerRef.current) {
      const headerHeight = 176 + 57 + 64; // 例如，顶部的搜索表单高度
      const footerHeight = 54; // 假设有一个底部的高度
      const windowHeight = window.innerHeight;
      const availableHeight = windowHeight - headerHeight - footerHeight;
      console.log("🚀🚀🚀 ~ updateTableHeight ~ availableHeight:", availableHeight)
      setTableHeight(availableHeight); // 更新表格高度
    }
  };
/**
 * 格式化表单值
 * @param {Object} values - 表单提交的原始值
 * @param {Object} fieldFormats - 字段格式化规则
 * @returns {Object} - 格式化后的表单值
 */
  const SearchValues = async () => {
    const values = await queryForm.validateFields();
    const filters = {
      page,
      pageSize,
      ...values,
      createTime: values.createTime ? values.createTime.format('YYYY-MM-DD') : '',
      updateTime: values.updateTime ? values.updateTime.format('YYYY-MM-DD') : ''
    };
    return filters
  };

  const handleSearch = async () => {
    let val = await SearchValues()
    console.log(val);
    fetchUsers(val);
  };
  const onReset = () => {
    console.log(containerRef);
    queryForm.resetFields();
    setPage(1)
    setPageSize(10)
    fetchUsers({page,pageSize});
  };
  const fetchUsers = async (filters = {}) => {
    try {
      setLoading(true);
      const response = await getUsers(filters);
      if (response.code === 200) {
        setTotal(response.data.pagination.total)
        setUsers(response.data.list);
      } else {
        message.error(response.error);
      }
    } catch (error) {
      console.error('获取用户列表错误:', error);
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchRoles = async () => {
    try {
      const response = await getRoles();
      if (response.code === 200) {
        setRoles(response.data);
      } else {
        message.error('获取角色列表失败');
      }
    } catch (error) {
      console.error('获取角色列表错误:', error);
      message.error('获取角色列表失败');
    }
  };

  const handleAddUser = () => {
    form.resetFields();
    setEditingUser(null);
    setModalVisible(true);
  };

  const handleEditUser = (user) => {
    form.resetFields();
    setEditingUser(user);
    form.setFieldsValue(user);
    setModalVisible(true);
  };

  const handleDeleteUser = async (userID) => {
    try {
      const response = await deleteUser(userID);
      if (response.code === 200) {
        message.success(response.message);
        fetchUsers({page,pageSize});
      } else {
        message.error(response.message || '删除用户失败');
      }
    } catch (error) {
      console.error('删除用户错误:', error);
      message.error('删除用户失败');
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      const userData = {
        username: values.username,
        password: values.password,
        email: values.email,
        phone: values.phone,
        nickname: values.nickname,
        role: values.role,
        createTime: new Date().toISOString()
      };

      if (editingUser) {
        // Update existing user
        const response = await updateUser(editingUser._id, userData);
        if (response.code === 200) {
          message.success(response.message);
          setModalVisible(false);
          fetchUsers({page,pageSize});
        }else{
          message.error(response.message);
        }
      } else {
        // Add new user
        const response = await addUser(userData);
        if (response.code === 200) {
          message.success(response.message);
          setModalVisible(false);
          fetchUsers({page,pageSize});
        }else{
          message.error(response.message);
        }
      }
    } catch (error) {
      console.error('保存用户错误:', error.response.data.message);
      message.error(error.response.data.message);
    }
  };

  const handleModalCancel = () => {
    form.resetFields();
    setModalVisible(false);
    setEditingUser(null);
  };
  const handleTableChange = async (page, pageSize) => {
    let val = await SearchValues()
    console.log(val);
    setPage(page)
    setPageSize(pageSize)
    fetchUsers({...val,page, pageSize});  // 调用接口，获取新分页的数据
  };
  const exportUsers = async () => {
    let hideLoading = null;
    try {
      if(selectedRowKeys.length === 0) {
        message.error('请先选择要导出的用户');
        return;
      }
      setExportLoading(true); // 开始加载
      hideLoading = messageApi.loading('正在生成导出文件，请稍候...', 0);
      const response = await getExportUsers(selectedRowKeys); // 调用 API 获取文件
      console.log(response); // 打印返回的数据
      // 检查是否返回 Blob 数据
        const blob = response;  // 直接获取 Blob 数据
        // const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    
        // 创建一个 Blob URL 用于下载文件
        const url = window.URL.createObjectURL(blob);
        
        // 创建一个下载链接并模拟点击下载文件
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '用户列表.xlsx'); // 设置文件名
        document.body.appendChild(link);
        link.click();
    
        // 释放 Blob URL
        window.URL.revokeObjectURL(url);
        
        
        // 可选: 在下载后显示成功消息
        message.success('用户列表导出成功');
     
    } catch (error) {
      console.error('导出用户错误:', error);
      message.error('导出用户失败');
    } finally {
      setExportLoading(false); // 结束加载
      if (hideLoading && typeof hideLoading === 'function') {
        hideLoading();
      }
    }
  };
  useEffect(() => {
    fetchUsers({page,pageSize});
    fetchRoles();
  }, []);
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      fixed: 'left',
      render: (_, __, index) => index + 1, // 简单使用 index+1
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      align: 'center',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
      align: 'center',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      align: 'center',
      render: (text) => text ? text : '-',
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
      align: 'center',
      render: (text) => text ? text : '-',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      render: (text) => new Date(text).toLocaleString().replace(/\//g, '-'),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      align: 'center',
      render: (text) => new Date(text).toLocaleString().replace(/\//g, '-'),
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      align: 'center',
      render: (role) => {
        const roleName = role ? ROLE_NAMES[role] : '-';
        const roleColor = role ? ROLE_COLORS[role] : 'default'; 
        return (
          <Tag color={roleColor}>
            {roleName}
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (_, record) => (
        <Space size="middle">
          <Tooltip
            title={
              !isSuperAdmin? '只有超级管理员可以编辑' : ''
            }
          >
            <Button
              type="link"
              icon={<EditOutlined />}
              disabled={!isSuperAdmin } // 判断当前登录用户角色
              onClick={() => handleEditUser(record)}
            >
              编辑
            </Button>
          </Tooltip>
          <Tooltip title={!isSuperAdmin ? '只有超级管理员可以删除' : ''}>
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              disabled={!isSuperAdmin}
              onClick={() => handleDeleteUser(record._id)}
            >
              删除
            </Button>
          </Tooltip>
        </Space>
      ),
    },
  ];
  

  // 定义表格的默认属性
  const tableProps = {
    columns:columns,
    dataSource: users,
    loading: loading,
    rowKey: "_id",
    // scroll: { x: 'max-content' },
    bordered: false,
    size: "middle",
    scroll:{ y: tableHeight },
    pagination: {
      defaultPageSize: 10,
      showSizeChanger: true,
      total:total,
      showTotal: (total) => `共 ${total} 条`,
      showQuickJumper: true,
      onChange: handleTableChange,
    },
    rowSelection: {
      type: "checkbox", // 设置为 "checkbox" 添加多选框
      onChange: (selectedRowKeys, selectedRows) => {
        setSelectedRowKeys(selectedRowKeys);
        console.log("Selected Row Keys:", selectedRowKeys);
        console.log("Selected Rows:", selectedRows);
      },
      getCheckboxProps: (record) => ({
        disabled: record.disabled, // 例如：根据条件禁用某些行的勾选框
      }),
    },
  };

  // 定义搜索字段
  const searchFields = [
    {
      name: 'username',
      label: '用户名',
      type: 'input',
      placeholder: '请输入用户名'
    },
    {
      name: 'phone',
      label: '电话',
      type: 'input',
      placeholder: '请输入电话'
    },
    {
      name: 'role',
      label: '角色',
      type: 'select',
      placeholder: '请选择角色',
      options: roles.map(role => ({
        value: role.code,
        label: role.name
      }))
    },
    {
      name: 'createTime',
      label: '创建时间',
      type: 'date',
      placeholder: '请选择创建时间'
    },
    {
      name: 'updateTime',
      label: '更新时间',
      type: 'date',
      placeholder: '请选择更新时间'
    },
    { label: '查询', type: 'button', buttonType: 'primary', htmlType: 'submit',style: {marginRight:'10px' } },
    { label: '重置', type: 'button', onClick: onReset ,style: {marginRight:'10px' }},
    { label: '添加', type: 'button', buttonType: 'primary', style: {marginRight:'10px' },onClick: handleAddUser },
    { label: '导出', type: 'button', buttonType: 'primary', onClick: exportUsers,loading: exportLoading,  // 绑定加载状态
    disabled: exportLoading } // 加载时禁用按钮,
  ];

  return (
    <div className="users-container">
      {contextHolder}
      <SearchForm
        form={queryForm}
        fields={searchFields}
        onSearch={handleSearch}
        onReset={onReset}
        onAdd={handleAddUser}
        addButtonText="添加用户"
        loading={loading}
      />
      <div ref={containerRef}>
        <Table {...tableProps} />
      </div>  
      <UserModal
        modalVisible={modalVisible}
        editingUser={editingUser}
        form={form}
        roles={roles}
        handleModalOk={handleModalOk}
        handleModalCancel={handleModalCancel}
      />
    </div>
  );
};

export default Users;
